<?php

namespace app\task\job;

use think\queue\Job;
use think\facade\Log;
use app\model\AdminSchoolDevice;
use app\common\service\face\FaceDevice;

/**
 * @Title: app\task\job$Demo
 * @author max
 * @date 2021年12月10日
 */
class SchoolDevice
{
    /**
     * 队列入口
     * @param Job $job
     * @param $data
     */
    public function fire(Job $job, $data)
    {
        $isJobDone = $this->handle($data);
        if ($isJobDone) {
            //如果任务执行成功，记得删除任务
            $job->delete();
        } else {
            //通过这个方法可以检查这个任务已经重试了几次了
            if ($job->attempts() > 1) {
                $job->delete();
            }
        }
    }

    /**
     * 处理
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($data)
    {
        if (empty($data['school_id']) || !is_numeric($data['school_id']) || empty($data['serial'])) {
            return false;
        }
        $m = new AdminSchoolDevice();
        //查找
        $info = $m->field('sd_id,serial_type')->where([
            'school_id' => $data['school_id'],
            'serial' => $data['serial'],
        ])->find();
        if (!empty($info['sd_id'])) {
            $updateData = [
                'device_id' => $data['device_id'],
                'heart_time' => $data['heart_time'],
                'update_time' => time(),
            ];
            $result = $m->where('sd_id', $info['sd_id'])->update($this->checkData($updateData, $data));
            $isBatchFace = false;
        } else {
            $insertData = [
                'school_id' => $data['school_id'],
                'serial_type' => $data['serial_type'],
                'serial' => $data['serial'],
                'device_id' => $data['device_id'],
                'heart_time' => $data['heart_time'],
                'create_time' => time(),
                'update_time' => time(),
            ];
            $result = $m->insert($this->checkData($insertData, $data));
            if ($insertData['serial_type'] == 2) {
                FaceDevice::batchAllPerson($data['school_id']);
            }
            $isBatchFace = $insertData['serial_type'] == 2;
        }
        if ($isBatchFace) {
            FaceDevice::batchAllPerson($data['school_id']);
        }
        return (bool)$result;
    }

    private function checkData($checkData, $data)
    {
        if (!empty($data['door_location'])) {
            $checkData['door_location'] = $data['door_location'];
        }
        if (!empty($data['door_status'])) {
            $checkData['door_status'] = $data['door_status'];
        }
        if (!empty($data['ip'])) {
            $checkData['ip'] = $data['ip'];
        }
        if (!empty($data['mac'])) {
            $checkData['mac'] = $data['mac'];
        }
        return $checkData;
    }
}